<template>
  <div class="work-order-pending page-container">
    <div class="page-header">
      <h2>待办查询（所有未完工工单）</h2>
      <div>
        <el-button @click="showColumnSettings" :icon="Setting">列设置</el-button>
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>

        <el-form-item v-if="visibleSearchFields.priority" label="优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable style="width: 120px">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="visibleSearchFields.dateRange" label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item v-if="visibleSearchFields.area" label="区域">
          <el-select v-model="searchForm.area" placeholder="请选择区域" clearable style="width: 200px">
            <el-option
              v-for="area in areas"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            />
          </el-select>
        </el-form-item>
        <!-- 动态自定义查询字段 -->
        <el-form-item 
          v-for="field in visibleSearchCustomFields" 
          :key="field.id"
          :label="field.label"
        >
          <el-input
            v-if="field.field_type === 'text' || field.field_type === 'textarea'"
            v-model="searchForm.customFields[field.name]"
            :placeholder="`请输入${field.label}`"
            clearable
            style="width: 200px"
          />
          <el-select
            v-else-if="field.field_type === 'select'"
            v-model="searchForm.customFields[field.name]"
            :placeholder="`请选择${field.label}`"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="option in getFieldOptions(field)"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
          <el-select
            v-else-if="field.field_type === 'checkbox'"
            v-model="searchForm.customFields[field.name]"
            :placeholder="`请选择${field.label}`"
            multiple
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="option in getFieldOptions(field)"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button @click="showSearchFieldSettings" :icon="Setting">查询字段设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工单列表 -->
    <el-card>
      <el-table
        :data="workOrders"
        v-loading="loading"
        stripe
        @row-click="viewDetail"
        style="cursor: pointer"
      >
        <el-table-column v-if="visibleColumns.order_number" prop="order_number" label="工单号" width="120" />
        <el-table-column v-if="visibleColumns.priority" prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="visibleColumns.status" prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="visibleColumns.creator_name" prop="creator_name" label="创建人" width="100" />
        <el-table-column v-if="visibleColumns.created_at" prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column v-if="visibleColumns.area_name" prop="area_name" label="区域" width="120" />
        <el-table-column v-if="visibleColumns.assignee_name" prop="assignee_name" label="处理人员" width="120" />
        <!-- 动态自定义字段列 -->
        <el-table-column 
          v-for="field in visibleCustomFields" 
          :key="field.id"
          :label="field.label"
          width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="getCustomFieldValue(row, field.id)" style="white-space: pre-line;">
              {{ getCustomFieldValue(row, field.id) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="viewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 列设置对话框 -->
    <el-dialog v-model="columnSettingsVisible" title="列显示设置" width="500px">
      <div class="column-settings">
        <h4>基础字段</h4>
        <el-checkbox-group v-model="selectedColumns">
          <div class="checkbox-item" v-for="column in availableColumns" :key="column.key">
            <el-checkbox :value="column.key" :label="column.label">{{ column.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
        
        <h4 style="margin-top: 20px;">自定义字段</h4>
        <el-checkbox-group v-model="selectedCustomFields">
          <div class="checkbox-item" v-for="field in customFields" :key="field.id">
            <el-checkbox :value="field.id" :label="field.label">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="columnSettingsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveColumnSettings">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查询字段设置对话框 -->
    <el-dialog v-model="searchFieldSettingsVisible" title="查询字段设置" width="500px">
      <div class="search-field-settings">
        <h4>基础查询字段</h4>
        <el-checkbox-group v-model="selectedSearchFields">
          <div class="checkbox-item" v-for="field in availableSearchFields" :key="field.key">
            <el-checkbox :value="field.key" :label="field.label">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
        
        <h4 style="margin-top: 20px;">自定义查询字段</h4>
        <el-checkbox-group v-model="selectedSearchCustomFields">
          <div class="checkbox-item" v-for="field in customFields" :key="field.id">
            <el-checkbox :value="field.id" :label="field.label">
              {{ field.label }}
              <el-tag v-if="['select', 'checkbox'].includes(field.field_type) && field.options" 
                     size="small" 
                     type="success" 
                     style="margin-left: 8px;">
                {{ field.field_type === 'select' ? '单选' : '多选' }}
              </el-tag>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="searchFieldSettingsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSearchFieldSettings">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Setting } from '@element-plus/icons-vue'
import { workOrdersApi, areasApi } from '@/api'
import { saveColumnSettings as saveColumnSettingsAPI, getColumnSettings, saveSearchFieldSettings as saveSearchFieldSettingsAPI, getSearchFieldSettings } from '@/api/userPreferences'

const router = useRouter()

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const searchForm = reactive({
  title: '',
  priority: '',
  dateRange: null as [string, string] | null,
  area: '',
  customFields: {} as Record<string, any>
})

const workOrders = ref([])
const areas = ref([])

// 列设置相关
const columnSettingsVisible = ref(false)
const customFields = ref([] as any[])

// 查询字段设置相关
const searchFieldSettingsVisible = ref(false)

// 可用的查询字段（从工单配置读取）
const availableSearchFields = ref([])

// 默认显示的查询字段
const selectedSearchFields = ref(['priority', 'dateRange', 'area'])
const selectedSearchCustomFields = ref([])

// 可用的基础列（从工单配置读取）
const availableColumns = ref([])

// 默认显示的列
const selectedColumns = ref(['order_number', 'priority', 'status', 'creator_name', 'created_at', 'area_name'])
const selectedCustomFields = ref([])

// 计算属性：可见的列
const visibleColumns = computed(() => {
  const result = {}
  selectedColumns.value.forEach(col => {
    result[col] = true
  })
  return result
})

// 计算属性：可见的自定义字段
const visibleCustomFields = computed(() => {
  if (!customFields.value || !Array.isArray(customFields.value)) {
    return []
  }
  return customFields.value.filter(field => selectedCustomFields.value.includes(field.id))
})

// 计算属性：可见的查询字段
const visibleSearchFields = computed(() => {
  const result = {}
  selectedSearchFields.value.forEach(field => {
    result[field] = true
  })
  return result
})

// 计算属性：可见的自定义查询字段
const visibleSearchCustomFields = computed(() => {
  if (!customFields.value || !Array.isArray(customFields.value)) {
    return []
  }
  return customFields.value.filter(field => selectedSearchCustomFields.value.includes(field.id))
})

// 获取字段选项
const getFieldOptions = (field: any) => {
  if (!field || (!['select', 'checkbox'].includes(field.field_type)) || !field.options) {
    return []
  }

  // 预处理输入
  const rawOptions = String(field.options).trim()
  
  // 优先尝试JSON解析（支持带引号和不带引号的数组）
  try {
    // 处理类似 "['选项1','选项2']" 的不规范JSON格式
    const sanitized = rawOptions
      .replace(/'/g, '"')
      .replace(/\[(.*)\]/, '$1')
    return JSON.parse(`[${sanitized}]`)
  } catch (jsonError) {
    // 严格字符串分割处理
    try {
      return rawOptions
        .split(',')
        .map(option => {
          // 移除首尾可能的JSON残留引号
          const cleaned = option.trim().replace(/^['"]|['"]$/g, '')
          return cleaned
        })
        .filter(option => option.length > 0)
    } catch (splitError) {
      console.error('字段选项解析失败:', {
        field: field.label,
        inputType: typeof field.options,
        originalInput: field.options,
        errors: {
          jsonError,
          splitError
        }
      })
      return []
    }
  }
}

const getPriorityType = (priority: string) => {
  const typeMap: Record<string, string> = {
    low: '',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return typeMap[priority] || ''
}

const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return textMap[priority] || priority
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    assigned: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

// 格式化日期为 yyyy/mm/dd
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 获取自定义字段值
const getCustomFieldValue = (row: any, fieldId: string) => {
  if (!row.custom_fields) return ''
  if (!customFields.value || !Array.isArray(customFields.value)) return ''
  
  // 根据字段ID查找对应的字段名
  const field = customFields.value.find(f => f.id === fieldId)
  if (!field) return ''
  
  const fieldData = row.custom_fields[field.name]
  if (!fieldData || !fieldData.value) return ''
  
  const value = fieldData.value
  
  // 处理不同类型的字段值
  if (fieldData.field_type === 'checkbox') {
    try {
      let parsedValue = JSON.parse(value)
      if (Array.isArray(parsedValue)) {
        // 去除双引号和方括号，确保多行显示
        parsedValue = parsedValue.map(item => String(item).replace(/^"|"$/g, ''))
        return parsedValue.join('\n')
      } else {
        return String(parsedValue).replace(/^"|"$/g, '')
      }
    } catch {
      return String(value).replace(/^\[|\]$/g, '').replace(/"/g, '')
    }
  }
  
  return String(value)
}

const loadWorkOrders = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      show_all: true, // 管理员显示所有工单
      priority: searchForm.priority,
      area: searchForm.area,
      start_date: searchForm.dateRange?.[0],
      end_date: searchForm.dateRange?.[1]
    }

    // 处理自定义字段查询参数，转换为customFields[字段名]格式
    for (const key in searchForm.customFields) {
      if (searchForm.customFields[key]) {
        params[`customFields[${key}]`] = searchForm.customFields[key]
      }
    }

    const response = await workOrdersApi.getWorkOrders(params)
    
    // 过滤出所有未完工的工单（pending, assigned, in_progress）
    const incompleteStatuses = ['pending', 'assigned', 'in_progress']
    const filteredWorkOrders = response.data.work_orders.filter(workOrder => 
      incompleteStatuses.includes(workOrder.status)
    )
    
    workOrders.value = filteredWorkOrders
    total.value = filteredWorkOrders.length
  } catch (error) {
    console.error('加载待办工单失败:', error)
    ElMessage.error('加载待办工单失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadWorkOrders()
}

onMounted(() => {
  loadWorkOrders()
})

const resetSearch = () => {
  searchForm.priority = ''
  searchForm.dateRange = null
  searchForm.area = ''
  searchForm.customFields = {}
  currentPage.value = 1
  loadWorkOrders()
}

const refreshData = () => {
  loadWorkOrders()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadWorkOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadWorkOrders()
}

const viewDetail = (row: any) => {
  router.push(`/work-orders/${row.id}`)
}

// 加载基础字段配置
const loadBasicFields = async () => {
  try {
    console.log('开始加载基础字段配置...')
    const response = await workOrdersApi.getFields({ field_category: 'basic', is_active: true })
    console.log('API响应:', response)
    
    const basicFields = response.data.fields || []
    console.log('获取到的基础字段:', basicFields)
    
    if (basicFields.length === 0) {
      console.warn('未获取到任何基础字段，使用默认配置')
      setDefaultFieldConfig()
      return
    }
    
    // 构建可用的基础列配置
    const columnMapping = {
      'order_number': '工单号',
      'title': '标题', 
      'priority': '优先级',
      'status': '状态',
      'type': '类型',
      'location': '位置',
      'notes': '备注',
      'assignee_id': '处理人员',
      'area_id': '区域',
      'scheduled_start': '计划开始时间',
      'scheduled_end': '计划结束时间'
    }
    
    // 从基础字段构建可用列
    const dynamicColumns = basicFields
      .filter(field => columnMapping[field.name])
      .map(field => ({
        key: field.name === 'area_id' ? 'area_name' : 
             field.name === 'assignee_id' ? 'assignee_name' :
             field.name,
        label: columnMapping[field.name] || field.label
      }))
    
    // 添加系统固定列（这些列不在字段配置中但需要显示）
    const systemColumns = [
      { key: 'creator_name', label: '创建人' },
      { key: 'created_at', label: '创建时间' }
    ]
    
    availableColumns.value = [...dynamicColumns, ...systemColumns]
    console.log('构建的可用列:', availableColumns.value)
    
    // 构建可用的查询字段配置
    const searchFieldMapping = {
      'priority': '优先级',
      'status': '状态',
      'type': '类型'
    }
    
    const dynamicSearchFields = basicFields
      .filter(field => searchFieldMapping[field.name] && field.field_type === 'select')
      .map(field => ({
        key: field.name,
        label: searchFieldMapping[field.name] || field.label
      }))
    
    // 添加系统固定查询字段
    const systemSearchFields = [
      { key: 'dateRange', label: '创建时间' },
      { key: 'area', label: '区域' }
    ]
    
    availableSearchFields.value = [...dynamicSearchFields, ...systemSearchFields]
    console.log('构建的可用查询字段:', availableSearchFields.value)
    
  } catch (error) {
    console.error('加载基础字段配置失败:', error)
    ElMessage.warning('加载字段配置失败，使用默认配置')
    setDefaultFieldConfig()
  }
}

// 设置默认字段配置
const setDefaultFieldConfig = () => {
  availableColumns.value = [
    { key: 'order_number', label: '工单号' },
    { key: 'priority', label: '优先级' },
    { key: 'status', label: '状态' },
    { key: 'creator_name', label: '创建人' },
    { key: 'created_at', label: '创建时间' },
    { key: 'area_name', label: '区域' }
  ]
  availableSearchFields.value = [
    { key: 'priority', label: '优先级' },
    { key: 'dateRange', label: '创建时间' },
    { key: 'area', label: '区域' }
  ]
  console.log('使用默认字段配置')
}

// 加载自定义字段
const loadCustomFields = async () => {
  try {
    const response = await workOrdersApi.getCustomFields()
    customFields.value = response.data.fields
    
    // 自动将带选项的自定义字段添加到查询字段设置中（如果还没有保存过设置）
    const savedSearchCustomFields = localStorage.getItem('workOrderPendingSearchCustomFields')
    if (!savedSearchCustomFields) {
      const fieldsWithOptions = customFields.value
        .filter(field => ['select', 'checkbox'].includes(field.field_type) && field.options)
        .map(field => field.id)
      selectedSearchCustomFields.value = fieldsWithOptions
    }
  } catch (error) {
    console.error('加载自定义字段失败:', error)
  }
}

// 显示列设置对话框
const showColumnSettings = () => {
  columnSettingsVisible.value = true
}

// 保存列设置
const saveColumnSettings = async () => {
  try {
    // 保存到服务器
    await saveColumnSettingsAPI('workOrderPending', {
      columns: selectedColumns.value,
      customFields: selectedCustomFields.value
    })
    
    // 同时保存到本地存储作为备份
    localStorage.setItem('workOrderPendingColumns', JSON.stringify(selectedColumns.value))
    localStorage.setItem('workOrderPendingCustomFields', JSON.stringify(selectedCustomFields.value))
    
    columnSettingsVisible.value = false
    ElMessage.success('列设置已保存')
  } catch (error) {
    console.error('保存列设置失败:', error)
    ElMessage.error('保存列设置失败，请重试')
  }
}

// 显示查询字段设置对话框
const showSearchFieldSettings = () => {
  searchFieldSettingsVisible.value = true
  
  // 如果没有选择任何自定义查询字段，提示用户选择带选项的字段
  if (selectedSearchCustomFields.value.length === 0) {
    const fieldsWithOptions = customFields.value.filter(field => 
      ['select', 'checkbox'].includes(field.field_type) && field.options
    )
    if (fieldsWithOptions.length > 0) {
      ElMessage.info(`提示：您可以选择带选项的自定义字段（如：${fieldsWithOptions.map(f => f.label).join('、')}）来启用下拉选择功能`)
    }
  }
}

// 保存查询字段设置
const saveSearchFieldSettings = async () => {
  try {
    // 保存到服务器
    await saveSearchFieldSettingsAPI('workOrderPending', {
      searchFields: selectedSearchFields.value,
      searchCustomFields: selectedSearchCustomFields.value
    })
    
    // 同时保存到本地存储作为备份
    localStorage.setItem('workOrderPendingSearchFields', JSON.stringify(selectedSearchFields.value))
    localStorage.setItem('workOrderPendingSearchCustomFields', JSON.stringify(selectedSearchCustomFields.value))
    
    searchFieldSettingsVisible.value = false
    ElMessage.success('查询字段设置已保存')
  } catch (error) {
    console.error('保存查询字段设置失败:', error)
    ElMessage.error('保存查询字段设置失败，请重试')
  }
}

// 从服务器和本地存储加载设置
const loadSettings = async () => {
  try {
    // 优先从服务器加载列设置
    const columnSettings = await getColumnSettings('workOrderPending')
    if (columnSettings && columnSettings.columns) {
      selectedColumns.value = columnSettings.columns
    }
    if (columnSettings && columnSettings.customFields) {
      selectedCustomFields.value = columnSettings.customFields
    }
    
    // 优先从服务器加载查询字段设置
    const searchFieldSettings = await getSearchFieldSettings('workOrderPending')
    if (searchFieldSettings && searchFieldSettings.searchFields) {
      selectedSearchFields.value = searchFieldSettings.searchFields
    }
    if (searchFieldSettings && searchFieldSettings.searchCustomFields) {
      selectedSearchCustomFields.value = searchFieldSettings.searchCustomFields
    }
    
    console.log('从服务器加载用户设置成功')
  } catch (error) {
    console.warn('从服务器加载用户设置失败，使用本地存储:', error)
    
    // 服务器加载失败时，从本地存储加载设置
    const savedColumns = localStorage.getItem('workOrderPendingColumns')
    const savedCustomFields = localStorage.getItem('workOrderPendingCustomFields')
    
    if (savedColumns) {
      selectedColumns.value = JSON.parse(savedColumns)
    }
    if (savedCustomFields) {
      selectedCustomFields.value = JSON.parse(savedCustomFields)
    }
    
    // 加载查询字段设置
    const savedSearchFields = localStorage.getItem('workOrderPendingSearchFields')
    const savedSearchCustomFields = localStorage.getItem('workOrderPendingSearchCustomFields')
    
    if (savedSearchFields) {
      selectedSearchFields.value = JSON.parse(savedSearchFields)
    }
    if (savedSearchCustomFields) {
      selectedSearchCustomFields.value = JSON.parse(savedSearchCustomFields)
    }
  }
}

// 加载区域选项
const loadAreas = async () => {
  try {
    const response = await areasApi.getAreaOptions()
    areas.value = response.data
  } catch (error) {
    console.error('加载区域选项失败:', error)
  }
}

onMounted(async () => {
  await loadSettings()
  loadBasicFields()
  loadCustomFields()
  loadAreas()
  loadWorkOrders()
})
</script>

<style scoped>
.work-order-pending {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.page-container {
  padding: 20px;
}

.column-settings {
  max-height: 400px;
  overflow-y: auto;
}

.column-settings h4 {
  margin: 10px 0;
  color: #333;
  font-size: 14px;
}

.checkbox-item {
  margin-bottom: 8px;
}

.checkbox-item .el-checkbox {
  width: 100%;
}
</style>
